<template>
  <h2>添加销售记录</h2>
  <el-form :model="saleForm" label-width="120px">
    <el-form-item label="选择客户">

      <div class="mt-4">
        <el-input
            v-model="input"
            style="min-width: 300px"
            placeholder="请输入关键字"
            class="input-with-select"
        >
          <template #prepend>
            <el-select v-model="select" placeholder="查询类型" style="width:130px">
              <el-option label="客户编号" value="id"/>
              <el-option label="客户姓名" value="custName"/>
              <el-option label="客户联系方式" value="phone"/>
            </el-select>
          </template>
          <template #append>
            <el-button :icon="Search" @click="handleSearch"/>
          </template>

        </el-input>

      </div>
    </el-form-item>
    <el-dialog v-model="dialogTableVisible" title="查询结果" width="500">
      <!-- 搜索结果列表 -->
      <el-table
          v-if="searchResult.length > 0"
          :data="searchResult"
          style="width: 100%;"
          @row-click="handleRowClick"
          highlight-current-row
          :row-class-name="rowClassName"
      >
        <el-table-column prop="id" label="客户编号"/>
        <el-table-column prop="custName" label="客户姓名"/>
        <el-table-column prop="phone" label="联系方式"/>
      </el-table>
    </el-dialog>

    <el-form-item label="已选客户">
      <div v-if="selectedCustomer" style="color: #666;">
        编号: {{ selectedCustomer.id }} 姓名：{{ selectedCustomer.custName }} 联系方式：{{ selectedCustomer.phone }}
      </div>
    </el-form-item>
    <!-- 选中项回显 -->

    <el-form-item label="销售渠道">
      <el-select v-model="saleForm.sourceChannelId" placeholder="请选择渠道" style="max-width: 300px">
        <el-option label="自媒体" value="0"/>
        <el-option label="网络推广" value="1"/>
        <el-option label="老客户介绍" value="2"/>
        <el-option label="线下推销" value="3"/>
        <el-option label="二次客户" value="4"/>
      </el-select>
    </el-form-item>
    <el-form-item label="预计成交金额">
      <el-input v-model="saleForm.expectedTransactionAmount" style="max-width: 300px"/>
    </el-form-item>
    <el-form-item label="当前阶段">
      <el-select v-model="saleForm.currentStage" placeholder="请选择" style="max-width: 300px">
        <el-option label="解除" value="解除"/>
        <el-option label="报价" value="报价"/>
        <el-option label="签约" value="签约"/>
      </el-select>
    </el-form-item>
    <el-form-item label="业务员">
      <el-input v-model="saleForm.empId" style="max-width: 300px"/>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="onSubmit">保存</el-button>
      <el-button @click="onCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import axios from "axios";
import {ElMessage} from "element-plus";
import {Search} from '@element-plus/icons-vue'

const input = ref('')
const select = ref('')
const dialogTableVisible = ref(false)
const search = ref({
  custName: null,
  phone: null,
  address: null
});

//定义销售过程表单
const saleForm = reactive({
  custId: null,
  sourceChannelId: null,
  expectedTransactionAmount: null,
  currentStage: null,
  empId: null
});

function handleSearch() {
  // 先清空所有 search 条件
  search.value = {
    custName: null,
    phone: null,
    address: null
  }
  console.log("search keyword:", input.value)
  console.log("search type:", select.value)
  if (select.value && input.value) {
    search.value[select.value] = input.value
  }
  console.log(search.value)
  dialogTableVisible.value = true

  const url = `http://localhost:52010/customer/page/1/10`

  // 只传递有值的搜索条件
  const params = {}
  Object.keys(search.value).forEach(key => {
    if (search.value[key]) {
      params[key] = search.value[key]
    }
  })

  axios.get(url, {params})
      .then(response => {
        const res = response.data
        if (res.code === 200) {
          searchResult.value = res.data.records || []
          if (res.data.total > 10) {
            ElMessage.warning('查询结果超过10个建议使用更精确的查询关键字或类型')
          }
        } else {
          ElMessage.error(res.message || '请求失败')
        }
      }).catch((error) => {
    const msg = error.response?.data?.message || error.message || '请求异常'
    ElMessage.error(msg)
  })

  selectedCustomer.value = null // 搜索后重置选择

}

const searchResult = ref([])  // 搜索结果数组
const selectedCustomer = ref(null) // 选中的客户

// 行点击选择
function handleRowClick(row) {
  selectedCustomer.value = row
  saleForm.custId = Number(row.id)
}

// table高亮选中行
function rowClassName({row}) {
  return selectedCustomer.value && row.id === selectedCustomer.value.id ? 'el-table__row--current' : ''
}

const onSubmit = () => {
  console.log('submit!')
  console.log("saleForm:", saleForm)
  axios.post("http://localhost:52010/sale/opportunity", saleForm).then((response) => {
    const res = response.data
    if (res.code === 200) {
      ElMessage({
        message: '添加成功！',
        type: 'success'
      })
    } else {
      ElMessage.error(res.message || '添加失败！')
    }
  }).catch((error) => {
    // 处理网络异常、服务器异常等
    // 尝试获取后端返回的 message
    const msg = error.response?.data?.message || error.message || '请求异常'
    ElMessage.error(msg)
  });
}

const onCancel = () => {
  console.log('cancel!')
  saleForm.custId = null
  saleForm.sourceChannelId = null
  saleForm.expectedTransactionAmount = null
  saleForm.currentStage = null
  saleForm.empId = null
  selectedCustomer.value = null
}
</script>

<style scoped>

</style>